var app = getApp()
var appData = app.globalData
var i, j, k     //点中桌下标
var ii, jj, kk  //换桌模式下的点中桌下标
var c = require('../../js/common.js')
Page({
    data: {
        tableList: null,    //餐桌列表
        tableIsShowArr: null,//餐桌分类(分区）是否显示
        clickTable: null,   //当前点中餐桌
        clickEvent: -1,
        do_mode: '',      //点击桌的两种操作模式（1正常，2：change换桌)
        statusArr: [//餐桌status可作为下标,然后循环调用按钮值
            ['点菜', '取消关桌'],                 //0是关桌状态
            ['点菜', '留座', '关桌'],             //1是空桌
            ['加菜', '查看菜单', '结账', '换桌', '取消开桌'],  //2是开桌
            ['点菜', '取消留座']                  //3是留座
        ],
        msg: [],
        msg_show: 0,
        btnArrIsShow: false,
        uid: ''
    },

    onLoad: function () {
        var user = appData.shopInfo
        this.data.uid = user.shopInfo.userid
        wx.setNavigationBarTitle({
            title: user.shopInfo.shop + '前台',
        })

        var t = this
        //开桌、加菜后通知更新界面
        app.setNoticeTableList(function (updateData) {
            var U = updateData
            if (U == 'reload') {
                t.onLoad()
            } else {
                if (U.cateId) { //如果是分类变更
                    t.updateTableCate(U)
                } else {
                    var table = t.data.tableList[i].list[j][k]
                    console.log('通知更新界面U：', U, '通知更新table：', table)
                    t.updateTableList(table, U)
                }
            }
        })

        var param = {
            uid: user.shopInfo.userid,
            seat_fee: user.shopInfo.seat_fee
        }
        app.getJsonData('api/space/table_list2.php', param, function (tableListData) {
            console.log('tableListData', tableListData)
            t.handleTableList(tableListData)
        })

        this.initWebsocket()
    },

    //扫描桌码得到店铺信息后方能启动
    initWebsocket: function () {
       var t = this
       app.readyWebsocket(function (callback) {
          console.log('初始化Websocket_回调值callback===' + callback)
          if (callback == 'initWebsocket_ok') {
             appData.wssIsInit = 1
             t.onSocketMsg()
          }
       })
    },

    handleTableList: function (data) {
        if (data.code == 0) {
            var obj = data.data
            this.setAppTableCateArr(obj)
            var isShow = []
            isShow.push(true)
            for (var i = 0; i < obj.length; i++) {
                isShow.push(true)
            }
            this.setData({
                tableIsShowArr: isShow,
                tableList: data.data,
            })
        }
    },

    readySendSocket: function (updateData) {
        var td = this.data
        var is_c = td.do_mode == 'change'
        var _msg
        var tab = td.tableList[i].list[j][k]
        if (td.clickEvent == 'change') {
            var tab2 = td.tableList[ii].list[jj][kk]
            _msg = tab.fenlei + tab.zhuo + '桌换到了' + tab2.fenlei + tab2.zhuo + '桌'
        } else {
            _msg = tab.fenlei + tab.zhuo + '桌' + td.clickEvent
        }
        var m = {
            msg: updateData,
            i: is_c ? ii : i,
            j: is_c ? jj : j,
            k: is_c ? kk : k,
            setMsg: _msg
        }//i,j,k必须要传，接收方才知道要更新哪张桌子
        var json = {
            type: 'say',
            to_client_id: 'all',
            content: JSON.stringify(m)
        }
        var msg = JSON.stringify(json)
        appData.isWsSender = 1
        app.sendSocketMsg(msg)
    },

    searchTable: function (table_id) {
        var list = this.data.tableList
        for (var i = 0; i < list.length; i++) {
            var list_j = list[i].list
            for (var j = 0; j < list_j.length; j++) {
                var list_k = list_j[j]
                for (var k = 0; k < list_k.length; k++) {
                    var tab = list_k[k]
                    if (tab.id == table_id) {
                        return tab
                    }
                }
            }
        }
    },

    onSocketMsg: function () {
        var t = this
        wx.onSocketMessage(function (res) {
            var data = JSON.parse(res.data)
            console.log('收到服务器消息转化成对象后：', data)
            if (data.notice) {
                var N = JSON.parse(data.notice)
                console.log('收到更新通知notice：', N)
                if (N.i) {
                    var tab = t.data.tableList[N.i].list[N.j][N.k]
                } else {
                    var tab = t.searchTable(N.msg[0])
                }
                console.log('全局appData.isWsSender前==', appData.isWsSender)
                if (appData.isWsSender == 0) {
                    t.updateTableList(tab, N.msg)
                    app.playMp3(N.msg[1])
                } else {
                    appData.isWsSender = 0
                }
                console.log('全局appData.isWsSender后==', appData.isWsSender)
                t.setMsg(N)
            }
        })
    },

    setMsg: function (N) {
        this.data.msg.unshift(N.setMsg + '  ' + c.getNowTime())
        this.setData({
            msg: this.data.msg,
            msg_show: 1
        })
        console.log('this.data.msg==', this.data.msg)
    },

    updateTableList: function (table, newData) {
        //newData数组结构：0桌号, 1状态, 2订单号, 3订单价格, 4点菜数量
        table.status = newData[1]
        if (newData[4]) {//加菜，因接口未做这个数量的累加
            var num = table.foodNum + newData[4]
        } else {//除加菜
            var num = newData[4]
        }
        if (newData.length > 2) {
            table.orderid = newData[2]
            table.totalPrice = newData[3]//.toFixed(2)
            table.foodNum = num
            table.guestNum = newData[5]
        }
        this.setData({
            tableList: this.data.tableList
        })
    },

    updateTableCate: function (newCate) {
        var N = newCate
        var list = this.data.tableList
        var arr = this.data.tableIsShowArr
        var index = this.getIndex(N.cateId, list)
        if (N.notice == 'del') {
            list.splice(index, 1)
            arr.splice(index, 1)
        } else if (index == -1) {
            list.push(N)
            arr.push(arr[0])
        } else {
            list[index].cateName = N.cateName
            list[index].cateSort = N.cateSort
        }

        console.log('updateTableCate:list', list)
        this.setData({
            tableList: list,
            tableIsShowArr: arr
        })
        this.setAppTableCateArr(list)
    },

    getIndex: function (id, list) {
        for (var i = 0; i < list.length; i++) {
            if (list[i].cateId == id) {
                return i
            }
        }
        return -1//表示没有
    },

    cancelChange: function () {
        this.setData({
            do_mode: ''
        })
    },

    tableClick: function (e) {
        var indexs = e.currentTarget.id.split(':');
        if (this.data.do_mode != 'change') {//非换桌模式下
            i = indexs[0]
            j = indexs[1]
            k = indexs[2]
            this.setData({
                btnArrIsShow: true,
                clickTable: this.data.tableList[i].list[j][k]
            })
        } else {//换桌模式
            ii = indexs[0]
            jj = indexs[1]
            kk = indexs[2]
            var newTable = this.data.tableList[ii].list[jj][kk]
            if (newTable.id == this.data.clickTable.id) {
                this.setData({ do_mode: '' })
            } else {
                this.eventHandle(newTable, 'change')
                this.setData({ clickTable: newTable })
            }
        }
    },
    // 点击弹框按钮效果
    tableEvent: function (e) {
        var table = this.data.tableList[i].list[j][k]
        var index = e.currentTarget.id
        var t = this
        var msg
        if (table.status == 0) {//状态:关桌
            if (index == 0) {
                msg = '开席了'
                this.openTable(table)
            } else if (index == 1) {//
                msg = '取消了关桌'
                this.eventHandle(table, 'open')
            }
        } else if (table.status == 1) {//状态:空桌
            if (index == 0) {
                msg = '开席了'
                this.openTable(table)
            } else if (index == 1) {
                msg = '留座了'
                this.eventHandle(table, 'keep')
            } else if (index == 2) {
                msg = '关桌了'
                this.eventHandle(table, 'close')
            }
        } else if (table.status == 2) {//状态开桌
            if (index == 0) {
                msg = '加菜了'
                this.openTable(table)
            } else if (index == 1) {
                msg = '查看菜单'
                let tableStr = JSON.stringify(this.data.clickTable)
                wx.navigateTo({
                    url: '/pages/01homePage/06order/manage?table=' + tableStr
                })
            } else if (index == 2) {
                msg = '去结账'
                let tableStr = JSON.stringify(this.data.clickTable)
                wx.navigateTo({
                    url: '/pages/01homePage/04bill/bill?table=' + tableStr
                })
            } else if (index == 3) {
                msg = 'change'
                this.setData({ do_mode: 'change' })
            } else if (index == 4) {
                msg = '取消了开桌'
                this.eventHandle(table, 'cancel')
            }
        } else if (table.status == 3) {//状态留座
            if (index == 0) {
                msg = '开席了'
                this.openTable(table)
            } else if (index == 1) {
                msg = '取消了留座'
                this.eventHandle(table, 'open')
            }
        }
        this.setData({
            btnArrIsShow: false,
            clickEvent: msg
        })
        console.log('this.data.clickEvent==' + this.data.clickEvent)
    },
    //开桌、加菜
    openTable: function (table) {
        let tableStr = JSON.stringify(table)
        wx.navigateTo({
            url: '/pages/01homePage/02openTable/openTable?table=' + tableStr
        })
    },
    //处理当前点中桌的事件参数：(桌，指令)
    eventHandle: function (table, command) {
        var param = {
            uid: appData.shopInfo.shopInfo.userid,
            command: command
        }
        var tab = this.data.tableList[i].list[j][k]//原点中桌
        if (command == 'change') {
            param.zhuo = tab.id
            param.newzhuo = table.id
        } else {
            param.zhuo = table.id
        }
        if (command == 'cancel') {
            param.orderid = table.orderid
        }
        console.log('param', param)
        var t = this
        app.getJsonData('api/space/table_status.php', param, function (res) {
            if (res.code == 0) {
                appData.isWsSender = 1
                if (command == 'change' || command == 'cancel') {
                    if (command == 'change') {
                        var notiNew = [table.id, 2, tab.orderid, tab.totalPrice, tab.foodNum, tab.guestNum]
                        console.log('换掉时notiNew：', notiNew)
                        t.updateTableList(t.data.tableList[ii].list[jj][kk], notiNew)
                        t.readySendSocket(notiNew)
                        t.setData({ do_mode: '' })
                    }
                    //当前桌置空
                    var noti = [tab.id, 1, '', 0, 0, 0]
                    console.log('换掉时当前桌置空noti：', notiNew)
                    t.updateTableList(t.data.tableList[i].list[j][k], noti)
                    t.readySendSocket(noti)
                } else {
                    console.log('关桌、留座时res.data：', res.data)
                    t.updateTableList(table, res.data)
                    t.readySendSocket(res.data)
                }
            }
        })
    },

    maskHide: function () {
        this.setData({
            btnArrIsShow: false
        })
    },

    pickerClick: function (e) {
        this.setData({ //选中picker
            index2: e.detail.value
        })
    },
    //存到全局变量中
    setAppTableCateArr: function (obj) {
        var table_cateArr = []
        for (var i = 0; i < obj.length; i++) {
            var tablbeCate = {
                cateId: obj[i].cateId,
                cateName: obj[i].cateName,
                cateSort: obj[i].cateSort,
            }
            table_cateArr.push(tablbeCate)
        }
        appData.tableCateArr = table_cateArr
    },

    clickCate: function (e) {
        var num = this.data.tableIsShowArr.length
        var index = Number(e.currentTarget.id)
        var isShow = []

        for (var i = 0; i < num; i++) {
            if (index == 0) {
                isShow.push(true)
            } else {
                isShow.push(index == i ? true : false)
            }
        }
        this.setData({
            tableIsShowArr: isShow
        })
        console.log(isShow)
        console.log('isShow')
    },

    onPullDownRefresh: function () {
        this.reload('下')
    },

    onReachBottom: function () {
        this.reload('上')
    },

    reload: function (msg) {
        app.toast(msg + '拉刷新了')
        this.onLoad()
    },

    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function () {
        console.log('生命周期函数--监听页面初次渲染完成')
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (opt) {
        console.log('生命周期函数--监听页面显示opt', opt)
        var appUser = appData.shopInfo
        console.log('this.data', this.data)
        if (appUser.shopInfo.userid != this.data.uid) {
            this.setData({
                msg: [],
                msg_show: 0
            })
            console.log('开始重载')
            this.onLoad()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('生命周期函数--监听页面隐藏')
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        console.log('生命周期函数--监听页面卸载')
    },

    showMsg: function () {
        this.setData({
            msg_show: this.data.msg_show ? 0 : 1
        })
    },

    onShareAppMessage: function () {
        var userInfoStr = JSON.stringify(appData.guestInfo)
        return {
            title: appData.guestInfo.name + '邀请您来【桥掌柜】当掌柜',
            path: '/pages/00login/login?str=' + userInfoStr
        }
    }
})